<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>API管理系统</title>
  <!-- 引入Element Plus样式 -->
  <link rel="stylesheet" href="https://unpkg.com/element-plus/dist/index.css">
  <!-- 引入Vue3和Element Plus -->
  <script src="https://unpkg.com/vue@3"></script>
  <script src="https://unpkg.com/element-plus"></script>
  <style>
    .api-container {
      padding: 20px;
      background-color: #f5f7fa;
      min-height: 100vh;
    }
    .api-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;
      padding-bottom: 15px;
      border-bottom: 1px solid #ebeef5;
    }
    .api-content {
      background: white;
      border-radius: 4px;
      padding: 20px;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    }
    .api-table {
      margin-top: 20px;
    }
    .api-run-dialog .el-dialog__body {
      padding-top: 10px;
    }
    .param-item {
      margin-bottom: 10px;
      padding: 10px;
      border: 1px solid #ebeef5;
      border-radius: 4px;
    }
    .env-selector {
      display: flex;
      align-items: center;
      margin-bottom: 15px;
    }
    .response-container {
      margin-top: 20px;
    }
    .response-headers {
      background-color: #f5f7fa;
      padding: 10px;
      border-radius: 4px;
      margin-bottom: 10px;
    }
  </style>
</head>
<body>
  <div id="app"></div>

  <script>
    const { createApp, ref, reactive, onMounted } = Vue;
    const { ElMessage, ElMessageBox } = ElementPlus;
    
    // API编辑组件
    const ApiEditor = {
      props: {
        apiData: {
          type: Object,
          default: () => ({})
        },
        isEdit: {
          type: Boolean,
          default: false
        }
      },
      emits: ['save', 'cancel'],
      setup(props, { emit }) {
        const form = reactive({
          name: '',
          url: '',
          method: 'GET',
          type: 'rest',
          preProcessor: '',
          postProcessor: '',
          params: [],
          headers: [],
          body: ''
        });
        
        const methodOptions = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS'];
        const typeOptions = [
          { label: 'REST API', value: 'rest' },
          { label: 'GraphQL', value: 'graphql' },
          { label: 'SOAP', value: 'soap' },
          { label: 'WebSocket', value: 'websocket' }
        ];
        const processorOptions = [
          { label: '无', value: '' },
          { label: 'JSON提取器', value: 'json' },
          { label: '正则表达式提取器', value: 'regex' },
          { label: 'XPath提取器', value: 'xpath' },
          { label: 'JavaScript处理器', value: 'javascript' }
        ];
        
        // 参数类型选项
        const paramTypeOptions = [
          { label: '文本', value: 'text' },
          { label: '文件', value: 'file' },
          { label: 'JSON', value: 'json' },
          { label: 'XML', value: 'xml' }
        ];
        
        // 初始化表单数据
        if (props.isEdit && props.apiData) {
          Object.assign(form, props.apiData);
        }
        
        // 添加参数
        const addParam = (type) => {
          if (type === 'params') {
            form.params.push({ key: '', value: '', type: 'text', description: '' });
          } else if (type === 'headers') {
            form.headers.push({ key: '', value: '', description: '' });
          }
        };
        
        // 删除参数
        const removeParam = (type, index) => {
          if (type === 'params') {
            form.params.splice(index, 1);
          } else if (type === 'headers') {
            form.headers.splice(index, 1);
          }
        };
        
        // 保存表单
        const saveForm = () => {
          // 简单验证
          if (!form.name || !form.url) {
            ElMessage.error('请填写API名称和URL');
            return;
          }
          
          emit('save', { ...form });
        };
        
        // 取消编辑
        const cancel = () => {
          emit('cancel');
        };
        
        return {
          form,
          methodOptions,
          typeOptions,
          processorOptions,
          paramTypeOptions,
          addParam,
          removeParam,
          saveForm,
          cancel
        };
      },
      template: `
        <div class="api-editor">
          <el-form :model="form" label-width="100px">
            <el-form-item label="API名称" required>
              <el-input v-model="form.name" placeholder="请输入API名称"></el-input>
            </el-form-item>
            
            <el-form-item label="请求URL" required>
              <el-input v-model="form.url" placeholder="请输入请求URL">
                <template #prepend>
                  <el-select v-model="form.method" style="width: 110px">
                    <el-option v-for="method in methodOptions" :key="method" :value="method"></el-option>
                  </el-select>
                </template>
              </el-input>
            </el-form-item>
            
            <el-form-item label="接口类型">
              <el-select v-model="form.type" placeholder="请选择接口类型">
                <el-option
                  v-for="item in typeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            
            <el-form-item label="前置处理器">
              <el-select v-model="form.preProcessor" placeholder="请选择前置处理器">
                <el-option
                  v-for="item in processorOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            
            <el-form-item label="后置处理器">
              <el-select v-model="form.postProcessor" placeholder="请选择后置处理器">
                <el-option
                  v-for="item in processorOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            
            <el-form-item label="请求参数">
              <div v-for="(param, index) in form.params" :key="index" class="param-item">
                <el-row :gutter="10">
                  <el-col :span="5">
                    <el-input v-model="param.key" placeholder="参数名"></el-input>
                  </el-col>
                  <el-col :span="5">
                    <el-select v-model="param.type" placeholder="类型">
                      <el-option
                        v-for="item in paramTypeOptions"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                      </el-option>
                    </el-select>
                  </el-col>
                  <el-col :span="10">
                    <el-input v-model="param.value" placeholder="参数值"></el-input>
                  </el-col>
                  <el-col :span="4">
                    <el-button @click="removeParam('params', index)" icon="el-icon-delete" type="danger"></el-button>
                  </el-col>
                </el-row>
                <el-input
                  v-model="param.description"
                  placeholder="参数描述"
                  style="margin-top: 5px">
                </el-input>
              </div>
              <el-button @click="addParam('params')" icon="el-icon-plus">添加参数</el-button>
            </el-form-item>
            
            <el-form-item label="请求头">
              <div v-for="(header, index) in form.headers" :key="index" class="param-item">
                <el-row :gutter="10">
                  <el-col :span="10">
                    <el-input v-model="header.key" placeholder="Header名"></el-input>
                  </el-col>
                  <el-col :span="10">
                    <el-input v-model="header.value" placeholder="Header值"></el-input>
                  </el-col>
                  <el-col :span="4">
                    <el-button @click="removeParam('headers', index)" icon="el-icon-delete" type="danger"></el-button>
                  </el-col>
                </el-row>
                <el-input
                  v-model="header.description"
                  placeholder="Header描述"
                  style="margin-top: 5px">
                </el-input>
              </div>
              <el-button @click="addParam('headers')" icon="el-icon-plus">添加Header</el-button>
            </el-form-item>
            
            <el-form-item label="请求体" v-if="['POST', 'PUT', 'PATCH'].includes(form.method)">
              <el-input
                v-model="form.body"
                type="textarea"
                :rows="6"
                placeholder="请输入请求体内容（JSON/XML等）">
              </el-input>
            </el-form-item>
            
            <el-form-item>
              <el-button type="primary" @click="saveForm">保存</el-button>
              <el-button @click="cancel">取消</el-button>
            </el-form-item>
          </el-form>
        </div>
      `
    };
    
    const App = {
      components: { ApiEditor },
      setup() {
        const apiList = ref([]);
        const showEditor = ref(false);
        const showRunner = ref(false);
        const editingApi = ref(null);
        const isEditMode = ref(false);
        const runningApi = ref(null);
        const environments = ref([
          { id: 1, name: '开发环境', url: 'https://dev.api.example.com' },
          { id: 2, name: '测试环境', url: 'https://127.0.0.1:8090' },
          { id: 3, name: '预发布环境', url: 'https://stage.api.example.com' },
          { id: 4, name: '生产环境', url: 'https://api.example.com' }
        ]);
        const currentEnvironment = ref(environments.value[0]);
        const responseData = ref(null);
        const loading = ref(false);
        
        // 初始化一些示例数据
        onMounted(() => {
          apiList.value = [
            {
              id: 1,
              name: '获取用户列表',
              url: '/users',
              method: 'GET',
              type: 'rest',
              params: [
                { key: 'page', value: '1', type: 'text', description: '页码' },
                { key: 'limit', value: '10', type: 'text', description: '每页数量' }
              ],
              headers: [
                { key: 'Content-Type', value: 'application/json', description: '内容类型' }
              ]
            },
            {
              id: 2,
              name: '创建新用户',
              url: '/users',
              method: 'POST',
              type: 'rest',
              params: [],
              headers: [
                { key: 'Content-Type', value: 'application/json', description: '内容类型' },
                { key: 'Authorization', value: 'Bearer token', description: '认证令牌' }
              ],
              body: JSON.stringify({ name: 'John Doe', email: 'john@example.com' }, null, 2)
            }
          ];
        });
        
        // 打开新增对话框
        const openAddDialog = () => {
          editingApi.value = {
            name: '',
            url: '',
            method: 'GET',
            type: 'rest',
            preProcessor: '',
            postProcessor: '',
            params: [],
            headers: [],
            body: ''
          };
          isEditMode.value = false;
          showEditor.value = true;
        };
        
        // 打开编辑对话框
        const openEditDialog = (api) => {
          editingApi.value = { ...api };
          isEditMode.value = true;
          showEditor.value = true;
        };
        
        // 保存API
        const saveApi = (apiData) => {
          if (isEditMode.value) {
            // 更新现有API
            const index = apiList.value.findIndex(item => item.id === editingApi.value.id);
            if (index !== -1) {
              apiList.value.splice(index, 1, { ...apiData, id: editingApi.value.id });
            }
          } else {
            // 新增API
            apiList.value.push({
              ...apiData,
              id: Date.now() // 简单生成ID
            });
          }
          showEditor.value = false;
          ElMessage.success(isEditMode.value ? '更新成功' : '添加成功');
        };
        
        // 删除API
        const deleteApi = (api) => {
          ElMessageBox.confirm(`确定要删除API "${api.name}" 吗？`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            apiList.value = apiList.value.filter(item => item.id !== api.id);
            ElMessage.success('删除成功');
          }).catch(() => {});
        };
        
        // 运行API
        const runApi = (api) => {
          runningApi.value = { ...api };
          responseData.value = null;
          showRunner.value = true;
        };
        
        // 执行API请求
        const executeApi = () => {
          loading.value = true;
          
          // 模拟API请求
          setTimeout(() => {
            loading.value = false;
            responseData.value = {
              status: 200,
              statusText: 'OK',
              headers: {
                'content-type': 'application/json',
                'date': new Date().toUTCString(),
                'server': 'nginx/1.18.0'
              },
              data: {
                success: true,
                message: '请求成功',
                data: [
                  { id: 1, name: '用户1', email: 'user1@example.com' },
                  { id: 2, name: '用户2', email: 'user2@example.com' },
                  { id: 3, name: '用户3', email: 'user3@example.com' }
                ]
              }
            };
          }, 1500);
        };
        
        return {
          apiList,
          showEditor,
          showRunner,
          editingApi,
          isEditMode,
          runningApi,
          environments,
          currentEnvironment,
          responseData,
          loading,
          openAddDialog,
          openEditDialog,
          saveApi,
          deleteApi,
          runApi,
          executeApi
        };
      },
      template: `
        <div class="api-container">
          <div class="api-header">
            <h1>API管理系统</h1>
            <el-button type="primary" icon="el-icon-plus" @click="openAddDialog">新增API</el-button>
          </div>
          
          <div class="api-content">
            <el-table :data="apiList" class="api-table" stripe>
              <el-table-column prop="name" label="API名称" width="180"></el-table-column>
              <el-table-column label="方法" width="80">
                <template #default="{row}">
                  <el-tag :type="row.method === 'GET' ? 'success' : row.method === 'POST' ? 'warning' : 'danger'">
                    {{ row.method }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="url" label="URL"></el-table-column>
              <el-table-column prop="type" label="类型" width="100">
                <template #default="{row}">
                  <el-tag>{{ row.type }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="240">
                <template #default="{row}">
                  <el-button size="small" @click="openEditDialog(row)">编辑</el-button>
                  <el-button size="small" type="primary" @click="runApi(row)">运行</el-button>
                  <el-button size="small" type="danger" @click="deleteApi(row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
          
          <!-- API编辑对话框 -->
          <el-dialog 
            :title="isEditMode ? '编辑API' : '新增API'" 
            v-model="showEditor" 
            width="800px"
            append-to-body>
            <ApiEditor 
              :api-data="editingApi" 
              :is-edit="isEditMode"
              @save="saveApi"
              @cancel="showEditor = false">
            </ApiEditor>
          </el-dialog>
          
          <!-- API运行对话框 -->
          <el-dialog 
            title="运行API" 
            v-model="showRunner" 
            width="900px"
            class="api-run-dialog"
            append-to-body>
            <div v-if="runningApi">
              <div class="env-selector">
                <span style="margin-right: 10px;">运行环境：</span>
                <el-select v-model="currentEnvironment" value-key="id" style="width: 200px;">
                  <el-option
                    v-for="env in environments"
                    :key="env.id"
                    :label="env.name"
                    :value="env">
                  </el-option>
                </el-select>
                <el-button type="primary" style="margin-left: 15px;" @click="executeApi" :loading="loading">
                  发送请求
                </el-button>
              </div>
              
              <el-divider></el-divider>
              
              <div>
                <h3>请求信息</h3>
                <p><strong>URL：</strong>{{ currentEnvironment.url }}{{ runningApi.url }}</p>
                <p><strong>方法：</strong>{{ runningApi.method }}</p>
                
                <div v-if="runningApi.params && runningApi.params.length">
                  <h4>请求参数：</h4>
                  <el-table :data="runningApi.params" size="small" border>
                    <el-table-column prop="key" label="参数名" width="120"></el-table-column>
                    <el-table-column prop="type" label="类型" width="80"></el-table-column>
                    <el-table-column prop="value" label="值"></el-table-column>
                    <el-table-column prop="description" label="描述"></el-table-column>
                  </el-table>
                </div>
                
                <div v-if="runningApi.headers && runningApi.headers.length">
                  <h4>请求头：</h4>
                  <el-table :data="runningApi.headers" size="small" border>
                    <el-table-column prop="key" label="Header名" width="150"></el-table-column>
                    <el-table-column prop="value" label="值"></el-table-column>
                    <el-table-column prop="description" label="描述"></el-table-column>
                  </el-table>
                </div>
                
                <div v-if="runningApi.body">
                  <h4>请求体：</h4>
                  <pre>{{ runningApi.body }}</pre>
                </div>
              </div>
              
              <div class="response-container" v-if="responseData">
                <h3>响应结果</h3>
                <p><strong>状态码：</strong> 
                  <el-tag :type="responseData.status === 200 ? 'success' : 'danger'">
                    {{ responseData.status }} {{ responseData.statusText }}
                  </el-tag>
                </p>
                
                <div class="response-headers" v-if="responseData.headers">
                  <h4>响应头：</h4>
                  <div v-for="(value, key) in responseData.headers" :key="key">
                    <strong>{{ key }}:</strong> {{ value }}
                  </div>
                </div>
                
                <div>
                  <h4>响应体：</h4>
                  <pre>{{ JSON.stringify(responseData.data, null, 2) }}</pre>
                </div>
              </div>
            </div>
          </el-dialog>
        </div>
      `
    };
    
    const app = createApp(App);
    app.use(ElementPlus);
    app.mount('#app');
  </script>
</body>
</html>